import {Upload, message} from 'antd';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';
import React, {useState} from 'react';

function beforeUpload(file) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt1M = file.size / 1024 / 1024 < 1;
  if (!isLt1M) {
    message.error('Image must smaller than 1MB!');
  }
  return isJpgOrPng && isLt1M;
}

function ImgUploader(props) {
  const [loading, setLoading] = useState(false);

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  const handleChange = ({file}) => {
    if (file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (file.status === 'done') {
      // Get this url from response in real world.
      // console.log(file.response.data.url)
      props.onUploaded(file.response.data.url);
      setLoading(false);
    }
  };

  return (
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={`https://evp.51job.com/51job/api/1.0/index.php/msd/index/upload?token=${localStorage.getItem('msd_token')}`}
      beforeUpload={beforeUpload}
      headers={{
        // 'Content-Type': 'application/x-www-form-urlencoded'
        // 'enctype': "multipart/form-data"
      }}
      onChange={handleChange}
    >
      {props.logo ?
        <img src={'http://cache.51job.com' + props.logo} alt="avatar" style={{width: '100%'}}/> : uploadButton}
    </Upload>
  );

}

export default ImgUploader;
